package com.aier.controller.foreign;



import com.aier.bean.common.CommonCode;
import com.aier.bean.common.CommonResult;
import com.aier.bean.common.GlobalCode;
import com.aier.bean.foreign.ForeignBase;
import com.aier.exception.CastException;
import com.aier.service.foreign.ForeignBaseService;
import com.alibaba.excel.EasyExcel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 外贸基础数据controller
 */

@Controller
@CrossOrigin
@RequestMapping("/foreign_base")
public class ForeignBaseController {

    @Autowired
    private ForeignBaseService foreignBaseService;

    @RequestMapping("/save")
    @ResponseBody
    public CommonResult saveForeignBase(@RequestBody ForeignBase foreignBase){
        foreignBaseService.saveForeignBase(foreignBase);
        return CommonResult.success();
    }

    @RequestMapping("/get_by_staff_id")
    @ResponseBody
    public CommonResult getForeignBaseByStaffId(@RequestBody Map<String,String> map){
        List<ForeignBase> foreignBaseList = foreignBaseService.getForeignBaseByStaffId(map.get("staffId"));
        return CommonResult.success(foreignBaseList);
    }

    @RequestMapping("/modify")
    @ResponseBody
    public CommonResult modifyForeignBase(@RequestBody ForeignBase foreignBase){
        foreignBaseService.modifyForeignBase(foreignBase);
        return CommonResult.success();
    }

    @RequestMapping("/remove_by_fba")
    @ResponseBody
    public CommonResult removeForeignBase(@RequestBody Map<String,String> map){
        foreignBaseService.removeForeignBase(map.get("fbaCode"));
        return CommonResult.success();
    }

    @RequestMapping("/save_forwarder_id")
    @ResponseBody
    public CommonResult saveForwarderId(@RequestBody Map<String,String> map){
        foreignBaseService.saveForwarderId(map.get("fbaCode"),map.get("forwarderId"),map.get("selfTaxed"));
        return CommonResult.success();
    }

    @RequestMapping("/batch_upload")
    @ResponseBody
    @Transactional
    public CommonResult batchUploadForeignBase(@RequestParam("file") MultipartFile file,         // 接收文件
                                               @RequestParam(value = "staffId") String staffId,            // 接收普通参数
                                               @RequestParam(value = "staffName") String staffName){
        try {
            //记录保存成功的fba
            List<String>successFbaCodeList = new ArrayList<>();
            //记录保存失败的fba
            List<String>failFbaCodeList = new ArrayList<>();
            List<ForeignBase> foreignBaseList = EasyExcel.read(file.getInputStream())
                    .head(ForeignBase.class)
                    .sheet()
                    .doReadSync();
            // 处理数据
            foreignBaseList.forEach(foreignBase->processForeignBase(foreignBase,successFbaCodeList,failFbaCodeList,staffId,staffName));
            Map<String,List<String>> result = new HashMap<>();
            result.put("success",successFbaCodeList);
            result.put("fail",failFbaCodeList);
            return CommonResult.success(result);
        } catch (IOException e) {
            e.printStackTrace();
            return CommonResult.error(GlobalCode.READ_FAIL);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.error(GlobalCode.EXPORT_FAIL);
        }
    }

    @GetMapping("/download_template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        // 1. 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("外贸基础数据模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 2. 创建空数据列表
        List<ForeignBase> emptyList = Collections.emptyList();

        // 3. 使用EasyExcel写入模板
        EasyExcel.write(response.getOutputStream(), ForeignBase.class)
                .sheet("基础数据")
                .doWrite(emptyList);
    }

    private void processForeignBase(ForeignBase foreignBase,List<String>successFbaCodeList,List<String>failFbaCodeList,String staffId,String staffName) {
        // 这里实现业务逻辑，例如：
        // 1. 数据校验
        if (foreignBase.getFbaCode() == null || foreignBase.getFbaCode().isEmpty()) {
            CastException.cast(GlobalCode.FBA_IS_EMPTY);
        }

        // 2. 枚举值转换（示例）
        foreignBase.setCountry(convertCountryCode(foreignBase.getCountry()));
        foreignBase.setPlatforms(convertPlatformCode(foreignBase.getPlatforms()));
        //添加负责业务员信息
        foreignBase.setStaffId(staffId);
        foreignBase.setStaffName(staffName);

        // 3. 保存到数据库（需要实现Mapper）
        ForeignBase foreignBaseByFbaCode = foreignBaseService.getForeignBaseByFbaCode(foreignBase.getFbaCode());
        if (foreignBaseByFbaCode == null){
            //不存在，则保存并记录成功fba
            foreignBaseService.saveForeignBase(foreignBase);
            successFbaCodeList.add(foreignBase.getFbaCode());
        }else {
            //存在，则记录失败fba
            failFbaCodeList.add(foreignBase.getFbaCode());
        }
        System.out.println("处理记录: " + foreignBase.toString());
    }

    private String convertCountryCode(String code) {
        // C01-美国，C02-加拿大
        AtomicReference<String> result = new AtomicReference<>(code);
        CommonCode.countryCode.forEach((key,value)->{
            if (code.equals(value)){
                result.set(key);
            }
        });
        return result.get();
    }

    private String convertPlatformCode(String code) {
        // P01-亚马逊
        AtomicReference<String> result = new AtomicReference<>(code);
        CommonCode.platformsCode.forEach((key,value)->{
            if (code.equals(value)){
                result.set(key);
            }
        });
        return result.get();
    }
}
